package com.gan.bi.rabbitmq;

import java.util.Date;

import com.gan.bi.common.ErrorCode;
import com.gan.bi.constant.CommonConstant;
import com.gan.bi.exception.BusinessException;
import com.gan.bi.manager.AiManager;
import com.gan.bi.model.entity.Chart;
import com.gan.bi.model.enums.ChartStatusEnum;
import com.gan.bi.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author gbw
 * @date 2023/7/20
 */
@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    ChartService chartService;

    @Resource
    AiManager aiManager;

    @RabbitListener(queues = {"ai_queue"}, ackMode = "MANUAL")
    private void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {

        if (StringUtils.isBlank(message)) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException("传入的消息为空!");
        }
        Chart chart = chartService.getById(Long.parseLong(message));
        if (chart == null) {
            throw new BusinessException("查询不到图表!");
        }

        Chart updateChart = new Chart();
        updateChart.setStatus(ChartStatusEnum.RUNNING.getValue());
        updateChart.setId(chart.getId());
        String answer = null;
        try {
            answer = aiManager.doChat(CommonConstant.AI_MODULE_ID, buildUserInput(chart));
        } catch (Exception e) {
            handleChartUpdateError(updateChart.getId(), "调用 AI 接口失败!");
            throw new BusinessException("调用 AI 接口失败!");
        }
        // 拆分回答
        String[] split = answer.split("【【【【【");
        if (split.length >= 4) {
            handleChartUpdateError(chart.getId(), "ai 返回错误!");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "ai 返回错误!");
        }

        String genChart = split[1];
        String genResult = split[2];
        updateChart.setStatus(ChartStatusEnum.SUCCEED.getValue());
        updateChart.setGenChart(genChart);
        updateChart.setGenResult(genResult);
        chartService.updateById(updateChart);
        // 消息确认
        channel.basicAck(deliveryTag, false);

        log.info("receiveMessage", message);

    }

    /**
     * 创建用户输入数据
     *
     * @param chart
     * @return
     */
    private String buildUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartData = chart.getChartData();
        String chartType = chart.getChartType();

        // 拼接用户输入的内容
        StringBuilder userInput = new StringBuilder();

        // "分析需求：\n分析网站用户增长情况\n原始数据：\n日期,用户数\n1号,10\n2号,20\n3号,30\n"
        userInput.append("分析需求：\n" + goal + "\n");
        if (StringUtils.isNotBlank(chartType)) {
            userInput.append("请使用:" + chartType + "\n");
        }
        userInput.append("原始数据:\n" + chartData);
        return userInput.toString();
    }


    /**
     * 处理执行失败时的回调
     *
     * @param chartId
     * @param execMessage
     */
    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus(ChartStatusEnum.FILED.getValue());
        chart.setExecMessage(execMessage);
        if (!chartService.updateById(chart)) {
            log.error("执行失败时，修改图表信息失败!");
        }
    }
}
